/*
 * Copyright 2002-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.deservel.wxopen.test;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author DeserveL
 * @date 2017/7/12 18:02
 * @since 1.0.0
 */
public class ChatServer {

    private int port = 8189;// 默认服务器端口

    public ChatServer() {
    }

    // 创建指定端口的服务器
    public ChatServer(int port) {
        this.port = port;
    }

    // 提供服务
    public void service() {
        try {// 建立服务器连接
            ServerSocket server = new ServerSocket(port);
            // 等待客户连接
            Socket socket = server.accept();
            try {
                // 读取客户端传过来信息的DataInputStream
                DataInputStream in = new DataInputStream(socket
                        .getInputStream());
                // 向客户端发送信息的DataOutputStream
                DataOutputStream out = new DataOutputStream(socket
                        .getOutputStream());
                // 获取控制台输入的Scanner
                Scanner scanner = new Scanner(System.in);
                Thread thread = new Thread() {
                    @Override
                    public void run() {
                        while(true){
                            String send = scanner.nextLine();
                            try {
                                out.writeUTF("服务器：" + send);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                };
                thread.start();
                while (true) {
                    // 读取来自客户端的信息
                    String accpet = in.readUTF();
                    System.out.println(accpet);
//                    String send = scanner.nextLine();
//                    System.out.println("服务器：" + send);
//                    // 把服务器端的输入发给客户端
//                    out.writeUTF("服务器：" + send);
                }
            } finally {// 建立连接失败的话不会执行socket.close();
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        new ChatServer().service();
    }
}
